package com.css.dzj.dzjjcss.modules.resultregister.service.impl;
import com.css.dzj.dzjjcss.common.util.Constant;
import com.css.dzj.dzjjcss.common.util.R;
import com.css.dzj.dzjjcss.common.util.ServiceUtil;
import com.css.dzj.dzjjcss.modules.resultregister.entity.ResultRegisterEntity;
import com.css.dzj.dzjjcss.modules.resultregister.entity.QResultRegisterEntity;
import com.css.dzj.dzjjcss.modules.resultregister.mapper.ResultRegisterMapper;
import com.css.dzj.dzjjcss.modules.resultregister.service.ResultRegisterService;
import com.css.dzj.dzjjcss.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service
public class ResultRegisterImpl implements ResultRegisterService{

    @Autowired
    private ResultRegisterMapper resultRegisterMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private ServiceUtil serviceUtil;

    @Autowired
    private HttpServletRequest request;
    /**
     * 新增
     */

    @Override
    @Transactional
    public void add(ResultRegisterEntity resultRegisterEntity) {

        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if (r.getCode().equals("200")) {
                LoginUser userInfo = (LoginUser) r.get("data");
                resultRegisterEntity.setCreateUser(userInfo.getLoginName());
                resultRegisterEntity.setCreateUserUnit(userInfo.getOrgName());
                resultRegisterEntity.setOrgLevel(userInfo.getOrgLevel());
                resultRegisterEntity.setOrgName(userInfo.getOrgName());
            }
            resultRegisterEntity.setDelFlag(Constant.NO_DELETE);
            resultRegisterEntity.setCreateTime(new Date());
            resultRegisterEntity.setStatus("1");
            resultRegisterEntity.setSubmitTime(new Date());
            resultRegisterEntity.setPxTime(new Date());
            resultRegisterMapper.save(resultRegisterEntity);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 暂存
     * @param resultRegisterEntity
     */
    @Override
    @Transactional
    public void addOnly(ResultRegisterEntity resultRegisterEntity) {
        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            if (r.getCode().equals("200")) {
                LoginUser userInfo = (LoginUser) r.get("data");
                resultRegisterEntity.setCreateUser(userInfo.getLoginName());
                resultRegisterEntity.setCreateUserUnit(userInfo.getOrgName());
                resultRegisterEntity.setOrgName(userInfo.getOrgName());
                resultRegisterEntity.setOrgLevel(userInfo.getOrgLevel());
            }
            resultRegisterEntity.setDelFlag(Constant.NO_DELETE);
            resultRegisterEntity.setCreateTime(new Date());
            resultRegisterEntity.setPxTime(new Date());
            resultRegisterEntity.setStatus("0");
            resultRegisterMapper.save(resultRegisterEntity);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public ResultRegisterEntity findById(String id) {
        return resultRegisterMapper.findById(id).get();
    }


    /**
     * 修改
     */
    @Override
    @Transactional
    public void update(ResultRegisterEntity resultRegisterEntity) {

    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public Boolean delete(String id) {

        QResultRegisterEntity qResultRegisterEntity = QResultRegisterEntity.resultRegisterEntity;
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("参数为空");
        }
        try {
            jpaQueryFactory
                    .update(qResultRegisterEntity)
                    .set(qResultRegisterEntity.delFlag, Constant.DELETE)
                    .where(
                            qResultRegisterEntity.id.eq(id),
                            qResultRegisterEntity.delFlag.eq(Constant.NO_DELETE)
                    )
                    .execute();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 多条件分页查询监管结果登记信息
     */
    @Override
    public QueryResults<ResultRegisterEntity> getSupervisionList(String createUser, String projectName, String administrativeDivision, String supervisionType, String createUserUnit, String status, String releaseStartTime, String releaseEndTime,String unitName,Pageable pageable){

        QResultRegisterEntity qResultRegisterEntity = QResultRegisterEntity.resultRegisterEntity;

        Predicate predicate = qResultRegisterEntity.isNotNull().or(qResultRegisterEntity.isNull());
        predicate = ("".equals(createUser) || createUser == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.createUser.like("%"+createUser+"%"));
        predicate = ("".equals(projectName) || projectName == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.projectName.like("%"+projectName+"%"));
        predicate = ("".equals(administrativeDivision) || administrativeDivision == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.administrativeDivision.like("%"+administrativeDivision+"%"));
        predicate = ("".equals(supervisionType) || supervisionType == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.supervisionType.eq(supervisionType));
        predicate = ("".equals(createUserUnit) || createUserUnit == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.createUserUnit.like("%"+createUserUnit+"%"));
        predicate = ("".equals(unitName) || unitName == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.unitName.like("%"+unitName+"%"));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, qResultRegisterEntity.status.eq(status));

        /* 只有结束时间*/
        if ((StringUtils.isEmpty(releaseStartTime)) && (!StringUtils.isEmpty(releaseEndTime))) {
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(releaseEndTime+ " " + "23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, qResultRegisterEntity.submitTime.loe(endDate));
        }
/** 只有开始时间 **/
        if ((!StringUtils.isEmpty(releaseStartTime)) && (StringUtils.isEmpty(releaseEndTime))) {
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse(releaseStartTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, qResultRegisterEntity.submitTime.goe(startDate));
        }
/** 时间都不为空 **/
        if ((!StringUtils.isEmpty(releaseStartTime)) && (!StringUtils.isEmpty(releaseEndTime))) {
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime);
                endDate = sfd.parse(releaseEndTime+ " " + "23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, qResultRegisterEntity.submitTime.between(startDate, endDate));
        }

        predicate = ExpressionUtils.and(predicate, qResultRegisterEntity.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qResultRegisterEntity)
                .where(
                        predicate
                )
                .orderBy(qResultRegisterEntity.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }



}
